package com.google.code.etrclient.xml;

import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.google.code.etrclient.pojo.Course;

public class XMLCoursesParseHandler extends DefaultHandler {
  private ArrayList<Course> courses;
  private Course parsedCourse;
  private boolean inCourseRow;
  private int tdCounter;
  
  public ArrayList<Course> getParsedData() {
    if (courses != null) {
      return courses;
    } else {
      return null;
    }
  }
  
  @Override
  public void startDocument() throws SAXException {
    courses = new ArrayList<Course>();
    tdCounter = 0;
  }
  
  @Override
  public void endDocument() throws SAXException {
  }
  
  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    try {
      if (localName.equalsIgnoreCase("tr") && (attributes.getValue("class").equalsIgnoreCase("sor1") || attributes.getValue("class").equalsIgnoreCase("sor0"))) {
        inCourseRow = true;
        Log.d("PARSER", "tr sor1/sor0");
      } else if (localName.equalsIgnoreCase("td")) {
        tdCounter++;
        Log.d("PARSER", "td #" + tdCounter);
      }
    } catch (Exception e) {
      Log.w("PARSER", "Exception: " + e.getClass());
    }
  }
  
  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    try {
      if (localName.equalsIgnoreCase("tr") && inCourseRow) {
        inCourseRow = false;
        tdCounter = 0;
        Log.d("PARSER", "tr end");
      } else if (localName.equalsIgnoreCase("td")) {
        Log.d("PARSER", "td #" + tdCounter + " end");
        if (tdCounter == 2 && parsedCourse != null) {
          courses.add(parsedCourse);
        }
      }
    } catch (Exception e) {
      Log.w("PARSER", "Exception: " + e.getClass());
    }
  }
  
  @Override
  public void characters(char[] ch, int start, int length) throws SAXException {
    try {
      if (tdCounter == 2) {
        String s = new String(ch, start, length);
        Log.d("PARSER", "Course: " + s + " (length: " + length + ")");
        parsedCourse = new Course(null, s, null, 0, 0, 0, 0, 0, false);
      }
    } catch (Exception e) {
      Log.w("PARSER", "Exception: " + e.getClass());
    }
  }
}
